package com.zhentao.controller;

import com.zhentao.pojo.*;
import com.zhentao.service.SalesOrderService;
import com.zhentao.service.SalesOrderItemService;
import com.zhentao.service.CustomerService;
import com.zhentao.service.ProductService;
import com.zhentao.service.SalesOutboundService;
import com.zhentao.service.SalesOutboundItemService;
import com.zhentao.service.WarehouseService;
import com.zhentao.service.SalesReturnService;
import com.zhentao.service.SalesReturnItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.math.BigDecimal;

// 添加必要的导入
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhentao.vo.SalesPageVo;
import com.zhentao.vo.SalesOutboundPageVo;
import com.zhentao.vo.SalesReturnPageVo;

/**
 * 销售管理控制器
 * @date: 2025/8/4 11:05
 * @author: ftt
 */

@RestController
@RequestMapping("sales")
public class SalesController {
    // 注入销售服务
    @Autowired
    private SalesOrderService salesOrderService;
    @Autowired
    private SalesOrderItemService salesOrderItemService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private ProductService productService;

    // 注入销售出库服务
    @Autowired
    private SalesOutboundService salesOutboundService;
    @Autowired
    private SalesOutboundItemService salesOutboundItemService;
    @Autowired
    private WarehouseService warehouseService;

    // 注入销售退货服务
    @Autowired
    private SalesReturnService salesReturnService;
    @Autowired
    private SalesReturnItemService salesReturnItemService;

    /**
     * 创建销售订单
     * @param salesOrder 销售订单对象
     * @return 创建的销售订单
     */
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public SalesOrder createSales(@RequestBody SalesOrder salesOrder) {
        try {
            // 自动生成订单号（如前端未传递）
            if (salesOrder.getOrderNo() == null || salesOrder.getOrderNo().trim().isEmpty()) {
                String orderNo = "SO" + new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
                salesOrder.setOrderNo(orderNo);
            }
            
            // 设置创建时间和用户信息
            salesOrder.setCreateTime(new java.util.Date());
            if (salesOrder.getTenantId() == null) {
                salesOrder.setTenantId(1L); // 默认租户ID
            }
            if (salesOrder.getStatus() == null) {
                salesOrder.setStatus(0); // 0表示未出库
            }
            
            // 保存销售订单主表
            salesOrderService.save(salesOrder);
            
            // 保存明细
            List<SalesOrderItem> items = salesOrder.getItems();
            if (items != null && !items.isEmpty()) {
                for (SalesOrderItem item : items) {
                    // 验证明细数据
                    if (item.getProductId() == null) {
                        throw new RuntimeException("产品ID不能为空");
                    }
                    if (item.getQuantity() == null || item.getQuantity().compareTo(java.math.BigDecimal.ZERO) <= 0) {
                        throw new RuntimeException("数量必须大于0");
                    }
                    if (item.getUnitPrice() == null || item.getUnitPrice().compareTo(java.math.BigDecimal.ZERO) < 0) {
                        throw new RuntimeException("单价不能为负数");
                    }
                    
                    // 设置订单ID
                    item.setOrderId(salesOrder.getId());
                    
                    // 保存明细
                    salesOrderItemService.save(item);
                }
            } else {
                throw new RuntimeException("销售订单明细不能为空");
            }
            
            return salesOrder;
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("创建销售订单失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("创建销售订单失败: " + e.getMessage());
        }
    }

    @GetMapping("/customer")
    public List<Customer> customerList(){
        return customerService.list();
    }

    /**
     * 删除销售订单
     * @param id 销售订单ID
     * @return 是否删除成功
     */
    @DeleteMapping("/{id}")
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSales(@PathVariable Long id) {
        try {
            // 验证订单是否存在
            SalesOrder existingOrder = salesOrderService.getById(id);
            if (existingOrder == null) {
                throw new RuntimeException("销售订单不存在");
            }

            // 先删除明细
            salesOrderItemService.lambdaUpdate()
                    .eq(SalesOrderItem::getOrderId, id)
                    .remove();
            
            // 再删除主表
            return salesOrderService.removeById(id);
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("删除销售订单失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("删除销售订单失败: " + e.getMessage());
        }
    }

    /**
     * 更新销售订单
     * @param salesOrder 销售订单对象
     * @return 更新后的销售订单
     */
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public SalesOrder updateSales(@RequestBody SalesOrder salesOrder) {
        try {
            // 验证订单是否存在
            if (salesOrder.getId() == null) {
                throw new RuntimeException("销售订单ID不能为空");
            }
            
            SalesOrder existingOrder = salesOrderService.getById(salesOrder.getId());
            if (existingOrder == null) {
                throw new RuntimeException("销售订单不存在");
            }

            // 更新订单主表
            salesOrderService.updateById(salesOrder);

            // 删除原有明细
            salesOrderItemService.lambdaUpdate()
                    .eq(SalesOrderItem::getOrderId, salesOrder.getId())
                    .remove();

            // 重新添加明细
            List<SalesOrderItem> items = salesOrder.getItems();
            if (items != null && !items.isEmpty()) {
                for (SalesOrderItem item : items) {
                    // 验证明细数据
                    if (item.getProductId() == null) {
                        throw new RuntimeException("产品ID不能为空");
                    }
                    if (item.getQuantity() == null || item.getQuantity().compareTo(java.math.BigDecimal.ZERO) <= 0) {
                        throw new RuntimeException("数量必须大于0");
                    }
                    if (item.getUnitPrice() == null || item.getUnitPrice().compareTo(java.math.BigDecimal.ZERO) < 0) {
                        throw new RuntimeException("单价不能为负数");
                    }
                    
                    // 设置订单ID
                    item.setOrderId(salesOrder.getId());
                    
                    // 保存明细
                    salesOrderItemService.save(item);
                }
            } else {
                throw new RuntimeException("销售订单明细不能为空");
            }

            return salesOrder;
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("更新销售订单失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("更新销售订单失败: " + e.getMessage());
        }
    }

    /**
     * 获取销售订单详情（包含明细）
     * @param id 销售订单ID
     * @return 包含详情的销售订单对象
     */
    @GetMapping("/withDetails/{id}")
    public SalesOrder getSalesWithDetails(@PathVariable Long id) {
        // 先获取销售订单主信息
        SalesOrder salesOrder = salesOrderService.getById(id);

        if (salesOrder != null) {
            Customer customer = customerService.getById(salesOrder.getCustomerId());
            if (customer != null) {
                salesOrder.setCustomerName(customer.getName());
            }

            // 获取该订单的所有详情项
            List<SalesOrderItem> items = salesOrderItemService.lambdaQuery()
                    .eq(SalesOrderItem::getOrderId, id)
                    .list();
            // 设置详情项到销售订单对象
            salesOrder.setItems(items);
            for (SalesOrderItem item : items) {
                Product product = productService.getById(item.getProductId());
                if (product != null) {
                    item.setProductName(product.getName());
                    item.setProductCode(product.getBarcode());
                }
            }
        }
        return salesOrder;
    }

    /**
     * 根据销售订单ID获取订单明细（用于出库单创建）
     * @param orderId 销售订单ID
     * @return 销售订单明细列表
     */
    @GetMapping("/orderItems/{orderId}")
    public List<SalesOrderItem> getSalesOrderItems(@PathVariable Long orderId) {
        // 获取该订单的所有详情项
        List<SalesOrderItem> items = salesOrderItemService.lambdaQuery()
                .eq(SalesOrderItem::getOrderId, orderId)
                .list();
        
        // 为每个明细项填充产品信息
        for (SalesOrderItem item : items) {
            Product product = productService.getById(item.getProductId());
            if (product != null) {
                item.setProductName(product.getName());
                item.setProductCode(product.getBarcode());
            }
        }
        return items;
    }

    /**
     * 分页获取销售订单
     * @param salesPageVo 分页参数
     * @return 分页销售订单列表
     */
    @PostMapping("/page")
    public Page<SalesOrder> getSalesPage(@RequestBody SalesPageVo salesPageVo) {
        LambdaQueryWrapper<SalesOrder> queryWrapper = Wrappers.<SalesOrder>lambdaQuery();

        if (StringUtils.hasText(salesPageVo.getOrderNo())) {
            queryWrapper.like(SalesOrder::getOrderNo, salesPageVo.getOrderNo());
        }

        if (StringUtils.hasText(salesPageVo.getCustomerName())) {
            queryWrapper.like(SalesOrder::getCustomerName, salesPageVo.getCustomerName());
        }

        if (StringUtils.hasText(salesPageVo.getStartDate())) {
            queryWrapper.gt(SalesOrder::getOrderDate, salesPageVo.getStartDate());
        }

        if (StringUtils.hasText(salesPageVo.getEndDate())) {
            queryWrapper.lt(SalesOrder::getOrderDate, salesPageVo.getEndDate());
        }

        // 如果排除已出库的订单，则过滤掉已经存在出库记录的销售订单
        if (salesPageVo.getExcludeOutbound() != null && salesPageVo.getExcludeOutbound()) {
            // 查询所有已经出库的订单ID
            List<SalesOutbound> outboundList = salesOutboundService.list();
            List<Long> outboundOrderIds = outboundList.stream()
                    .map(SalesOutbound::getOrderId)
                    .distinct()
                    .collect(java.util.stream.Collectors.toList());
            
            if (!outboundOrderIds.isEmpty()) {
                queryWrapper.notIn(SalesOrder::getId, outboundOrderIds);
            }
        }

        Page<SalesOrder> page = salesOrderService.page(
                new Page<>(salesPageVo.getPageNum(), salesPageVo.getPageSize()),
                queryWrapper
        );

        List<SalesOrder> records = page.getRecords();
        for (SalesOrder record : records) {
            Customer customer = customerService.getById(record.getCustomerId());
            if (customer != null) {
                record.setCustomerName(customer.getName());
            }
        }

        return page;
    }

    /**
     * 销售出库操作
     * @param outbound 销售出库单对象
     * @return 出库单对象
     */
    @PostMapping("/outbound")
    @Transactional(rollbackFor = Exception.class)
    public SalesOutbound createSalesOutbound(@RequestBody SalesOutbound outbound) {
        try {
            // 1. 验证销售订单是否存在
            Long orderId = outbound.getOrderId();
            if (orderId == null) {
                throw new RuntimeException("销售订单ID不能为空");
            }
            
            SalesOrder salesOrder = salesOrderService.getById(orderId);
            if (salesOrder == null) {
                throw new RuntimeException("销售订单不存在");
            }

            // 2. 自动生成出库单号（如果前端未传递）
            if (outbound.getOutboundNo() == null || outbound.getOutboundNo().trim().isEmpty()) {
                String outboundNo = "SO" + new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").format(new java.util.Date());
                outbound.setOutboundNo(outboundNo);
            }

            // 3. 设置创建时间和用户信息
            outbound.setCreateTime(new java.util.Date());
            if (outbound.getTenantId() == null) {
                outbound.setTenantId(1L); // 默认租户ID
            }

            // 4. 保存出库单主表
            salesOutboundService.save(outbound);

            // 5. 处理出库单明细
            List<SalesOutboundItem> items = outbound.getItems();
            if (items != null && !items.isEmpty()) {
                for (SalesOutboundItem item : items) {
                    // 验证明细数据
                    if (item.getProductId() == null) {
                        throw new RuntimeException("产品ID不能为空");
                    }
                    if (item.getQuantity() == null || item.getQuantity().compareTo(java.math.BigDecimal.ZERO) <= 0) {
                        throw new RuntimeException("数量必须大于0");
                    }
                    
                    // 设置出库单ID
                    item.setOutboundId(outbound.getId());
                    
                    // 保存明细
                    salesOutboundItemService.save(item);
                }
            } else {
                throw new RuntimeException("出库单明细不能为空");
            }

            // 6. 更新销售订单状态为已出库
            salesOrder.setStatus(1);
            salesOrderService.updateById(salesOrder);

            return outbound;
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("创建销售出库单失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("创建销售出库单失败: " + e.getMessage());
        }
    }

    /**
     * 分页获取销售出库单
     * @param outboundPageVo 分页参数
     * @return 分页销售出库单列表
     */
    @PostMapping("/outbound/page")
    public Page<SalesOutbound> getSalesOutboundPage(@RequestBody SalesOutboundPageVo outboundPageVo) {
        LambdaQueryWrapper<SalesOutbound> queryWrapper = Wrappers.<SalesOutbound>lambdaQuery();

        if (StringUtils.hasText(outboundPageVo.getOutboundNo())) {
            queryWrapper.like(SalesOutbound::getOutboundNo, outboundPageVo.getOutboundNo());
        }

        if (outboundPageVo.getOrderId() != null) {
            queryWrapper.eq(SalesOutbound::getOrderId, outboundPageVo.getOrderId());
        }

        if (StringUtils.hasText(outboundPageVo.getStartDate())) {
            queryWrapper.gt(SalesOutbound::getOutboundDate, outboundPageVo.getStartDate());
        }

        if (StringUtils.hasText(outboundPageVo.getEndDate())) {
            queryWrapper.lt(SalesOutbound::getOutboundDate, outboundPageVo.getEndDate());
        }

        // 如果排除已退货的出库单，则过滤掉已经存在退货记录的出库单
        if (outboundPageVo.getExcludeReturn() != null && outboundPageVo.getExcludeReturn()) {
            // 查询所有已经退货的出库单ID
            List<SalesReturn> returnList = salesReturnService.list();
            List<Long> returnOutboundIds = returnList.stream()
                    .map(SalesReturn::getOutboundId)
                    .distinct()
                    .collect(java.util.stream.Collectors.toList());
            
            if (!returnOutboundIds.isEmpty()) {
                queryWrapper.notIn(SalesOutbound::getId, returnOutboundIds);
            }
        }

        Page<SalesOutbound> page = salesOutboundService.page(
                new Page<>(outboundPageVo.getPageNum(), outboundPageVo.getPageSize()),
                queryWrapper
        );

        List<SalesOutbound> records = page.getRecords();
        for (SalesOutbound record : records) {
            // 获取关联的销售订单信息
            SalesOrder order = salesOrderService.getById(record.getOrderId());
            if (order != null) {
                record.setOrderNo(order.getOrderNo());
            }
            Warehouse warehouse = warehouseService.getById(record.getWarehouseId());
            if (warehouse != null) {
                record.setWarehouseName(warehouse.getName());
            }
        }

        return page;
    }

    @GetMapping("/warehouse")
    public List<Warehouse> warehouseList(){
        return warehouseService.list();
    }

    /**
     * 获取销售出库单详情（包含明细）
     * @param id 销售出库单ID
     * @return 包含详情的销售出库单对象
     */
    @GetMapping("/outbound/withDetails/{id}")
    public SalesOutbound getSalesOutboundWithDetails(@PathVariable Long id) {
        // 先获取销售出库单主信息
        SalesOutbound salesOutbound = salesOutboundService.getById(id);

        if (salesOutbound != null) {
            // 获取关联的销售订单信息
            SalesOrder order = salesOrderService.getById(salesOutbound.getOrderId());
            if (order != null) {
                salesOutbound.setOrderNo(order.getOrderNo());
            }

            // 获取仓库信息
            Warehouse warehouse = warehouseService.getById(salesOutbound.getWarehouseId());
            if (warehouse != null) {
                salesOutbound.setWarehouseName(warehouse.getName());
            }

            // 获取该出库单的所有详情项
            List<SalesOutboundItem> items = salesOutboundItemService.lambdaQuery()
                    .eq(SalesOutboundItem::getOutboundId, id)
                    .list();
            // 设置详情项到销售出库单对象
            salesOutbound.setItems(items);
            for (SalesOutboundItem item : items) {
                Product product = productService.getById(item.getProductId());
                if (product != null) {
                    item.setProductName(product.getName());
                    item.setProductCode(product.getBarcode());
                }
            }
        }
        return salesOutbound;
    }

    /**
     * 更新销售出库单
     * @param salesOutbound 销售出库单对象
     * @return 更新后的销售出库单
     */
    @PutMapping("/outbound")
    @Transactional(rollbackFor = Exception.class)
    public SalesOutbound updateSalesOutbound(@RequestBody SalesOutbound salesOutbound) {
        try {
            // 验证出库单是否存在
            if (salesOutbound.getId() == null) {
                throw new RuntimeException("出库单ID不能为空");
            }
            
            SalesOutbound existingOutbound = salesOutboundService.getById(salesOutbound.getId());
            if (existingOutbound == null) {
                throw new RuntimeException("出库单不存在");
            }

            // 更新出库单主表
            salesOutboundService.updateById(salesOutbound);

            // 删除原有明细
            salesOutboundItemService.lambdaUpdate()
                    .eq(SalesOutboundItem::getOutboundId, salesOutbound.getId())
                    .remove();

            // 重新添加明细
            List<SalesOutboundItem> items = salesOutbound.getItems();
            if (items != null && !items.isEmpty()) {
                for (SalesOutboundItem item : items) {
                    // 验证明细数据
                    if (item.getProductId() == null) {
                        throw new RuntimeException("产品ID不能为空");
                    }
                    if (item.getQuantity() == null || item.getQuantity().compareTo(java.math.BigDecimal.ZERO) <= 0) {
                        throw new RuntimeException("数量必须大于0");
                    }
                    
                    // 设置出库单ID
                    item.setOutboundId(salesOutbound.getId());
                    
                    // 保存明细
                    salesOutboundItemService.save(item);
                }
            } else {
                throw new RuntimeException("出库单明细不能为空");
            }

            return salesOutbound;
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("更新销售出库单失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("更新销售出库单失败: " + e.getMessage());
        }
    }

    /**
     * 删除销售出库单
     * @param id 销售出库单ID
     * @return 是否删除成功
     */
    @DeleteMapping("/outbound/{id}")
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSalesOutbound(@PathVariable Long id) {
        try {
            // 验证出库单是否存在
            SalesOutbound existingOutbound = salesOutboundService.getById(id);
            if (existingOutbound == null) {
                throw new RuntimeException("出库单不存在");
            }

            // 先删除明细
            salesOutboundItemService.lambdaUpdate()
                    .eq(SalesOutboundItem::getOutboundId, id)
                    .remove();

            // 再删除主表
            boolean result = salesOutboundService.removeById(id);
            
            if (result) {
                // 如果删除成功，需要将对应的销售订单状态改回未出库
                SalesOrder salesOrder = salesOrderService.getById(existingOutbound.getOrderId());
                if (salesOrder != null) {
                    salesOrder.setStatus(0); // 0表示未出库
                    salesOrderService.updateById(salesOrder);
                }
            }
            
            return result;
        } catch (Exception e) {
            // 记录错误日志
            System.err.println("删除销售出库单失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("删除销售出库单失败: " + e.getMessage());
        }
    }

    /**
     * 创建销售退货单
     * @param salesReturn 销售退货单对象
     * @return 创建的销售退货单
     */
    @PostMapping("/return")
    @Transactional(rollbackFor = Exception.class)
    public SalesReturn createSalesReturn(@RequestBody SalesReturn salesReturn) {
        try {
            // 1. 验证销售出库单是否存在
            Long outboundId = salesReturn.getOutboundId();
            if (outboundId == null) {
                throw new RuntimeException("出库单ID不能为空");
            }
            
            SalesOutbound salesOutbound = salesOutboundService.getById(outboundId);
            if (salesOutbound == null) {
                throw new RuntimeException("销售出库单不存在");
            }

            // 2. 自动生成退货单号
            String returnNo = "SR" + System.currentTimeMillis();
            salesReturn.setReturnNo(returnNo);
            
            // 3. 设置创建时间和用户信息
            salesReturn.setCreateTime(new java.util.Date());
            salesReturn.setTenantId(salesReturn.getTenantId() != null ? salesReturn.getTenantId() : 1);
            
            // 4. 验证商品明细
            List<SalesReturnItem> items = salesReturn.getItems();
            if (items == null || items.isEmpty()) {
                throw new RuntimeException("商品明细不能为空");
            }
            
            for (SalesReturnItem item : items) {
                if (item.getProductId() == null) {
                    throw new RuntimeException("商品ID不能为空");
                }
                if (item.getQuantity() == null || item.getQuantity().compareTo(BigDecimal.ZERO) <= 0) {
                    throw new RuntimeException("商品数量必须大于0");
                }
                if (item.getUnitPrice() == null || item.getUnitPrice().compareTo(BigDecimal.ZERO) < 0) {
                    throw new RuntimeException("商品单价不能为负数");
                }
            }

            // 5. 保存退货单主表
            salesReturnService.save(salesReturn);

            // 6. 处理退货单明细
            return getSalesReturn(salesReturn);
            
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("创建销售退货单失败: " + e.getMessage());
        }
    }

    /**
     * 分页获取销售退货单
     * @param returnPageVo 分页参数
     * @return 分页销售退货单列表
     */
    @PostMapping("/return/page")
    public Page<SalesReturn> getSalesReturnPage(@RequestBody SalesReturnPageVo returnPageVo) {
        LambdaQueryWrapper<SalesReturn> queryWrapper = Wrappers.<SalesReturn>lambdaQuery();

        if (StringUtils.hasText(returnPageVo.getReturnNo())) {
            queryWrapper.like(SalesReturn::getReturnNo, returnPageVo.getReturnNo());
        }

        if (returnPageVo.getOutboundId() != null) {
            queryWrapper.eq(SalesReturn::getOutboundId, returnPageVo.getOutboundId());
        }

        if (StringUtils.hasText(returnPageVo.getStartDate())) {
            queryWrapper.gt(SalesReturn::getReturnDate, returnPageVo.getStartDate());
        }

        if (StringUtils.hasText(returnPageVo.getEndDate())) {
            queryWrapper.lt(SalesReturn::getReturnDate, returnPageVo.getEndDate());
        }

        Page<SalesReturn> page = salesReturnService.page(
                new Page<>(returnPageVo.getPageNum(), returnPageVo.getPageSize()),
                queryWrapper
        );

        List<SalesReturn> records = page.getRecords();
        for (SalesReturn record : records) {
            // 获取关联的销售出库单信息
            SalesOutbound outbound = salesOutboundService.getById(record.getOutboundId());
            if (outbound != null) {
                record.setOutboundNo(outbound.getOutboundNo());
            }
            Warehouse warehouse = warehouseService.getById(record.getWarehouseId());
            if (warehouse != null) {
                record.setWarehouseName(warehouse.getName());
            }
        }

        return page;
    }

    /**
     * 获取销售退货单详情（包含明细）
     * @param id 销售退货单ID
     * @return 包含详情的销售退货单对象
     */
    @GetMapping("/return/withDetails/{id}")
    public SalesReturn getSalesReturnWithDetails(@PathVariable Long id) {
        // 先获取销售退货单主信息
        SalesReturn salesReturn = salesReturnService.getById(id);

        if (salesReturn != null) {
            // 获取关联的销售出库单信息
            SalesOutbound outbound = salesOutboundService.getById(salesReturn.getOutboundId());
            if (outbound != null) {
                salesReturn.setOutboundNo(outbound.getOutboundNo());
                // 获取关联的销售订单信息
                SalesOrder order = salesOrderService.getById(outbound.getOrderId());
                if (order != null) {
                    salesReturn.setOrderNo(order.getOrderNo());
                }
            }

            // 获取仓库信息
            Warehouse warehouse = warehouseService.getById(salesReturn.getWarehouseId());
            if (warehouse != null) {
                salesReturn.setWarehouseName(warehouse.getName());
            }

            // 获取该退货单的所有详情项
            List<SalesReturnItem> items = salesReturnItemService.lambdaQuery()
                    .eq(SalesReturnItem::getReturnId, id)
                    .list();
            // 设置详情项到销售退货单对象
            salesReturn.setItems(items);
            for (SalesReturnItem item : items) {
                Product product = productService.getById(item.getProductId());
                if (product != null) {
                    item.setProductName(product.getName());
                    item.setProductCode(product.getBarcode());
                }
            }
        }
        return salesReturn;
    }

    /**
     * 更新销售退货单
     * @param salesReturn 销售退货单对象
     * @return 更新后的销售退货单
     */
    @PutMapping("/return")
    public SalesReturn updateSalesReturn(@RequestBody SalesReturn salesReturn) {
        // 更新退货单主表
        salesReturnService.updateById(salesReturn);

        // 删除原有明细
        salesReturnItemService.lambdaUpdate()
                .eq(SalesReturnItem::getReturnId, salesReturn.getId())
                .remove();

        // 重新添加明细
        return getSalesReturn(salesReturn);
    }

    private SalesReturn getSalesReturn(@RequestBody SalesReturn salesReturn) {
        List<SalesReturnItem> items = salesReturn.getItems();
        if (items != null && !items.isEmpty()) {
            for (SalesReturnItem item : items) {
                item.setReturnId(salesReturn.getId());
                salesReturnItemService.save(item);
            }
        }

        return salesReturn;
    }

    /**
     * 删除销售退货单
     * @param id 销售退货单ID
     * @return 是否删除成功
     */
    @DeleteMapping("/return/{id}")
    public boolean deleteSalesReturn(@PathVariable Long id) {
        // 先删除明细
        salesReturnItemService.lambdaUpdate()
                .eq(SalesReturnItem::getReturnId, id)
                .remove();

        // 再删除主表
        return salesReturnService.removeById(id);
    }
}
       